package com.ly.elastic.service.impl;

import com.ly.elastic.pojo.User;
import com.ly.elastic.service.UserRepository;
import com.ly.elastic.service.UserService;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @Author LY
 * @create 2024/1/17 11:46
 * @Description 用户接口实现
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    private UserRepository dataRepository;
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    public void setDataRepository(UserRepository dataRepository) {
        this.dataRepository = dataRepository;
    }

    @Override
    public void save(User user) {
        // 保存信息
        dataRepository.save(user);
    }

    @Override
    public void deleteById(String id) {
        // 根据id删除
        dataRepository.deleteById(id);
    }

    @Override
    public User queryUserById(String id) {
        // 根据id查询
        Optional<User> optionalUser = dataRepository.findById(id);
        return optionalUser.get();
    }

    @Override
    public Iterable<User> queryAll() {
        // 查询所有
        return dataRepository.findAll();
    }

    @Override
    public Page<User> findByName(String name, PageRequest request) {
        // 按名称查询
        return dataRepository.findByName(name, request);
    }

    @Override
    public boolean createIndex(String indexName) {
        // 创建索引
        boolean isTrue = false;
        try {
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            isTrue = response.isAcknowledged();// 查看是否创建成功
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return isTrue;
    }

    @Override
    public boolean deleteIndex(String indexName) {
        // 删除索引
        boolean isTrue = false;
        try {
            DeleteIndexRequest request = new DeleteIndexRequest(indexName);
            AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
            isTrue = response.isAcknowledged();// 是否删除成功
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return isTrue;
    }

    @Override
    public boolean isIndexIsExists(String indexName) {
        // 查找索引是否存在
        GetIndexRequest request = new GetIndexRequest(indexName);
        boolean exists = false;
        try {
            exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return exists;
    }

    @Override
    public List<Map<String, Object>> search(String keyword, Integer pageIndex, Integer pageSize) {
        // 根据keyword分页查询结果
        if (pageIndex < 0){
            pageIndex = 0;
        }
        // 创建索引
        SearchRequest indexName = new SearchRequest("stack");
        // 创建搜索源建造者对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 条件采用：精确查询 通过keyword查字段name
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));// 60s
        // 分页
        searchSourceBuilder.from(pageIndex);
        searchSourceBuilder.size(pageSize);
        // 添加高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);
        // 搜索源放入搜索请求中
        indexName.source(searchSourceBuilder);
        // 执行查询，返回结果
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(indexName, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 解析结果
        SearchHits hits = searchResponse.getHits();
        List<Map<String,Object>> results = new ArrayList<>();
        for (SearchHit documentFields : hits.getHits()) {
            // 使用新的字段值（高亮），覆盖旧的字段值
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            // 高亮字段
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            // 高亮替换
            if (name != null){
                Text[] fragments = name.fragments();
                StringBuilder new_name = new StringBuilder();
                for (Text text : fragments) {
                    new_name.append(text);
                }
                sourceAsMap.put("name",new_name.toString());
            }
            results.add(sourceAsMap);
        }
        // 返回查询的结果
        return results;
    }

}
